#pragma once
#include <string>


namespace wyl
{
#define FILE_CODE "./getcode/code.txt"

    class CodeManager
    {
    public:
        CodeManager(){}

        bool ReadCodes()
        {
            int fd = open(FILE_CODE,O_RDONLY);
            if(fd < 0) {
                logMessage(ERROR,"open %s failed",FILE_CODE);
                return false; 
            }
            char buff[16*1024]; 
            //没找到返回false 
            int n = read(fd,buff,sizeof buff - 1); 
            if(n <= 0)
            {
                close(fd);
                logMessage(DEBUG,"read %s failed or is empty",FILE_CODE);
                return false;
            }
            buff[n] = 0;
            close(fd);  
            _codes = new std::string(buff);
            return true;
        }

        //读取code
        // void ReadCodes(const std::string& path) 
        // {

        // }

        bool DeleteCode()
        {
            //删除
            std::string new_codes; 
            size_t pos = _codes->find(_del_code); 
            new_codes += _codes->substr(0,pos); 
            new_codes += _codes->substr(pos + _del_code.size() + 1);
            delete _codes;
            _codes = new std::string(new_codes);
            if(!WriteCode())return false;
            return true;
        }

        bool FindCode(std::string code)
        {
            logMessage(DEBUG,"begin find code ....");
            if(_codes == nullptr) logMessage(DEBUG,"_codes == nullptr");
            code += "\n";
            int pos = _codes->find(code);
            return pos != std::string::npos; 
        }

        bool WriteCode()
        {
            int fd = open(FILE_CODE,O_WRONLY | O_TRUNC);
            if(fd < 0)
            {
                logMessage(ERROR,"open file failed");
                return false;
            }
            write(fd,_codes->c_str(),_codes->size());
            close(fd);
            return true;
        }

        void SetDeleteCode(const std::string& del_code)
        {
            _del_code = del_code;
        }

    private:
        std::string* _codes;
        std::string _del_code;
    };
};